import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import store from '@/store'
let originPush = VueRouter.prototype.push;
VueRouter.prototype.push = function(location,res,error){
  if(res&&error){
    originPush.call(this,location,res,error);
  }
  else{
    originPush.call(this,location,()=>{}, ()=>{ })}
}

Vue.use(VueRouter)

 



let router= new VueRouter({
  routes,
  scrollBehavior(to,from,savePosition){
    return {y:0};
  }
})

//全局守卫
router.beforeEach(async (to,from,next)=>{
  next();
    //捞token
    let token = store.state.user.token;
    let name = store.state.user.userInfo.name;
   if(token){
      //用户如果已经登陆了，还想去登录界面
      if (to.path == "/login") {
        next('/home');
    } 
    }
    //未登录不能去 的界面,跳转到登录界面
    else {
      let toPath =to.path;
     if(toPath.indexOf('/trade')!=-1 || toPath.indexOf('/pay')!=-1 || toPath.indexOf('/center')!=-1){
       next('/login?redirect='+toPath);
     }
     else{
       next();
     }
    }

})
export default router;